package com.leave.mos.service.impl;

import com.leave.mos.constant.TablenameConstant;
import com.leave.mos.entity.User;
import com.leave.mos.service.MongodbService;
import com.mongodb.client.result.UpdateResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class MongodbServiceImpl implements MongodbService {

    private final static Logger logger = LoggerFactory.getLogger(MongodbServiceImpl.class);

    @Resource
    private MongoTemplate mongoTemplate;

    /**
     * 创建对象
     * 保存数据到mg  如果有匹配到数集合中id值则更新数据，
     *              如果没有id字段，或者没有匹配到，则插入。
     * @param user
     */
    @Override
    public void saveUser(User user) {

        User userDb = mongoTemplate.save(user, TablenameConstant.Testabc.TableName);
        if (userDb != null) {
            logger.info("保存成功。。。。{}",user);
            return;
        }
        logger.error("保存失败");
    }

    /**
     * 根据用户名查询对象
     *
     * @param userName
     * @return
     */
    @Override
    public User findOneUser(String userName) {
        Query query = new Query(Criteria.where(TablenameConstant.Testabc.username).is(userName));
        User user = mongoTemplate.findOne(query, User.class, TablenameConstant.Testabc.TableName);
        return user;
    }

    /**
     * 更新对象
     *
     * @param user
     */
    @Override
    public long updateUser(User user) {
        Query query = new Query(Criteria.where(TablenameConstant.Testabc.id).is(user.getId()));
        Update update = new Update().set(TablenameConstant.Testabc.username, user.getUsername())
                .set(TablenameConstant.Testabc.passwrod, user.getPassword());
        //更新查询返回结果集的第一条
        //UpdateResult result = mongoTemplate.updateFirst(query, update,User.class,TablenameConstant.Testabc.TableName);
        //更新查询返回结果集的所有
        UpdateResult result = mongoTemplate.updateMulti(query,update,User.class,TablenameConstant.Testabc.TableName);
        if (result != null) {
            return result.getMatchedCount();
        } else {
            return 0;
        }
    }

    /**
     * 删除对象
     *
     * @param id
     */
    @Override
    public void removeUserById(String id) {
        Query query = new Query(Criteria.where(TablenameConstant.Testabc.id).is(id));
        mongoTemplate.remove(query, User.class,TablenameConstant.Testabc.TableName);
    }
}
